package hn.cch.servlet.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@WebServlet(urlPatterns = "/web/block", asyncSupported = true)
public class BlockServlet extends HttpServlet {


    private static final Logger logger = LoggerFactory.getLogger(BlockServlet.class);

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 异步上下文
        final AsyncContext asyncContext = req.startAsync();
        try {
            // 设置读取监听器
            req.getInputStream().setReadListener(new ReadListener() {
                @Override
                public void onDataAvailable() throws IOException {
                    new ServletUtils().asyncRead(asyncContext);
                }

                @Override
                public void onAllDataRead() throws IOException {

                    // 线程池
                    executor.execute(() -> {
                        new ServletUtils().asyncRun(resp, asyncContext);
                    });
                }

                @Override
                public void onError(Throwable throwable) {
                    logger.error("error:", throwable);
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        logger.info("service");

    }
}
